package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.OrderDto;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.service.OrderDetailService;
import com.itheima.reggie.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 订单
 */
@Slf4j
@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private OrderService orderService;


    @Autowired
    private OrderDetailService orderDetailService;

    /**
     * 提交订单
     * @param orders
     * @return
     */
    @PostMapping("/submit")
    public R submit(@RequestBody Orders orders) {
        log.info("提交订单：{}", orders);
        orderService.submit(orders);
        return R.success("提交订单成功！");
    }

    /**
     * 管理端订单明细
     * @return
     */
    @GetMapping("/page")
    public R page(int page, int pageSize,String number,String beginTime,String endTime){
        log.info("page={},pageSize={}",page,pageSize);
        //构造分页器对象
        Page<Orders> pageInfo = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Orders>queryWrapper=new LambdaQueryWrapper<>();
        //添加过滤条件
        queryWrapper.like(number!= null,Orders::getId, number);
        queryWrapper.ge(beginTime!= null,Orders::getOrderTime,beginTime);
        queryWrapper.le(endTime!= null,Orders::getOrderTime,endTime);
        //添加排序条件
        queryWrapper.orderByDesc(Orders::getCheckoutTime);
        //执行查询
        orderService.page(pageInfo,queryWrapper);

        List<Orders> records=pageInfo.getRecords();
        records=records.stream().map((item)->{
            item.setUserName("用户"+item.getConsignee());
            return item;
        }).collect(Collectors.toList());
        return R.success(pageInfo);
    }
     /* @GetMapping("/Page")
    public R page(int page, int pageSize, String name,String beginTime,String endTime,String number) {
        log.info("{}", beginTime);
        //构造分页器对象
        Page<Orders> orderPage = new Page<>(page, pageSize);
        //构造条件构造器
        LambdaQueryWrapper<Orders> lqw = new LambdaQueryWrapper<>();
        //根据订单号查询
        //如果前端传过来的number订单号不是空的，就用订单表中的订单号和前端传过来的订单号对比
        lqw.eq(StringUtils.isNotEmpty(number), Orders::getNumber, number);
        //时间
        //判断开始时间不为空，判断条件为...之间    这里是两个时间之间
        lqw.between(beginTime != null, Orders::getOrderTime, beginTime, endTime);
        //排序
        //按照时间降序排序
        lqw.orderByDesc(Orders::getCheckoutTime);
        //
        orderService.page(orderPage, lqw);
        //返回结果
        return R.success(orderPage);
    }
*/


    /**
     * 订单状态修改代码
     * @param map
     * @return
     */
    @PutMapping
    public R<String>orderStatusChanged(@RequestBody Map<String,String>map){
        String id=map.get("id");
        Long orderId = Long.parseLong(id);
        Integer status =Integer.parseInt(map.get("status"));

        if (orderId == null||status== null){
            return R.error("传入的消息不合法");
        }
        Orders orders =orderService.getById(id);
        orders.setStatus(status);
        orderService.updateById(orders);
        return R.success("订单状态修改成功");
    }


    /**
     * 用户端订单页面显示
     * @param page
     * @param pageSize
     * @return
     */
    @GetMapping("/userPage")
    public R Page(int page, int pageSize){
        //页面构造器
        Page<Orders> pageInfo=new Page<>(page,pageSize);
        Page<OrderDto> pageDto=new Page<>(page,pageSize);

        LambdaQueryWrapper<Orders> lqw =new LambdaQueryWrapper<>();
        //获取登录用户id
        lqw.eq(Orders::getUserId, BaseContext.getCurrentId());
        //根据更新时间排序
        lqw.orderByDesc(Orders::getOrderTime);
        orderService.page(pageInfo, lqw);
        BeanUtils.copyProperties(pageInfo,pageDto,"records");
        List<Orders> ordersList = pageInfo.getRecords();
        List<OrderDto> orderDtoList=new ArrayList<>();
        for (Orders orders : ordersList) {
            LambdaQueryWrapper<OrderDetail> lambdaQueryWrapper=new LambdaQueryWrapper<>();
            //根据用户id查询订单明细
            lambdaQueryWrapper.eq(OrderDetail::getOrderId,orders.getId());
            List<OrderDetail> orderDetailList = orderDetailService.list(lambdaQueryWrapper);

            //对orderDto进行订单明细赋值
            OrderDto orderDto = new OrderDto();
            BeanUtils.copyProperties(orders,orderDto);
            orderDto.setOrderDetails(orderDetailList);
            orderDtoList.add(orderDto);
        }
        pageDto.setRecords(orderDtoList);
        return R.success(pageDto);
    }


    /**
     * 再来一单
     * @param order
     * @return
     */
    @PostMapping("/again")
    public R again(@RequestBody Orders order){
        log.info("订单order为 {}",order);
        orderService.again(order);
        return R.success("下单成功");
    }

}